package cn.may.controller;

import cn.may.domain.Result;
import cn.may.domain.student.Student;
import cn.may.service.StudentService;
import cn.may.service.impl.StudentServiceImpl;
import cn.may.utils.ExcelUtil;
import cn.may.utils.ResultUtil;
import cn.may.utils.WordUtil;
import cn.may.utils.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipOutputStream;

/**
 * @author mayuanbao
 * @date 2019-06-02 10:44
 */
@RestController
public class StudentController {
    private static final Logger logger = LoggerFactory.getLogger(StudentServiceImpl.class);
    @Resource(name = "studentService")
    StudentService studentService;

    @PostMapping(value = "/getStudents")
    public List<Student> getStudent() {
        logger.info("method: " + "getStudent()");
        return studentService.findAll();
    }

    @PostMapping(value = "/addStudents")
    public Result addStudent(@Valid Student student, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            logger.info(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
            return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultUtil.success(studentService.addStudent(student));
    }

    @GetMapping(value = "/findByName")
    public Student findByName(Student student) {
        return studentService.findByName(student.getName());
    }

    @GetMapping(value = "/getById/{id}")
    public Student getById(@PathVariable("id") Integer id) throws Exception {
        return studentService.getById(id);
    }

    @GetMapping(value = "/exportStudent")
    public List<Student> exportStudent() {
        //查询
        List<Student> students = getStudent();
        //表头
        String[] titles = {"编号", "姓名", "年龄", "性别"};
        //路径
        String path = "F:/student_01.xls";
        try {
            ExcelUtil.exportExcel(students, titles, path);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return students;
    }

    @GetMapping("/exportToWord")
    public boolean exprotToWord() {
        List<Student> students = getStudent();
        // 组装word页面需要的数据
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("name", "may");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        dataMap.put("date", sdf.format(new Date()));
        dataMap.put("content", "freemark生成word文档");
        List<Map<String, Object>> listInfo = new ArrayList<>();
        for (Student student : students) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", student.getId());
            map.put("name", student.getName());
            map.put("age", student.getAge());
            map.put("sex", student.getSex() == 1 ? "男" : "女");
            listInfo.add(map);
        }
        dataMap.put("listInfo", listInfo);
        String templateName = "students.ftl";
        return WordUtil.exportWord(dataMap, templateName);
    }

    @GetMapping("/exportToZip")
    public String exportToZip() throws Exception {
        // 要压缩的文件
        String sourcePath = "F:/source/";
        File sourceFile = new File(sourcePath);
        System.out.println(sourceFile);
        if (!sourceFile.exists()) {
            return "文件不存在";
        }
        // 压缩后文件
        String zipPath = "F:/source.zip";
        FileOutputStream out = new FileOutputStream(zipPath);
        ZipOutputStream zipOutputStream = new ZipOutputStream(out);
        // 压缩
        String result = ZipUtil.zip(sourceFile, sourceFile.getName(),zipOutputStream);
        zipOutputStream.close();
        out.close();
        return result;
    }

    @PostMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public Student update() {
        Student student = new Student();
        student.setName("周芷若");
        student.setAge(20);
        student.setSex(0);
        Student student1 = new Student();
        student1.setName("赵敏");
        student1.setAge(22);
//        student1.setSex(1);
        studentService.addStudent(student);
        return studentService.addStudent(student1);
    }

    @GetMapping("/delete/{id}")
    @Transactional(rollbackFor = Exception.class)
    public int delete(@PathVariable(value = "id") Integer id) {
        Student student = new Student();
        student.setName("周芷若");
        student.setAge(20);
        student.setSex(0);
        studentService.addStudent(student);
        return studentService.deleteById(id);
    }
}
